package com.wframe.project.former.task;

import com.frame.database.JdataBean;
import com.github.binarywang.wxpay.bean.WxPayOrderNotifyResponse;
import com.github.binarywang.wxpay.bean.result.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.gson.Gson;
import com.wframe.project.jnd.entity.Payment;
import com.wframe.project.jnd.services.OrderService;
import com.wframe.project.jnd.services.PayService;
import com.wframe.project.jnd.wx.wxImpl.WeixAccountConfig;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/20.
 */
@Component
public class PaymentTask {

    @Autowired
    private PayService payService;

    @Autowired
    private WeixAccountConfig tempWechatConfig;

    @Autowired
    private OrderService orderService;

    private static WxPayConfig wechatPayConfig;

    private static WxPayService wxPayService;

    private void initWechatConfig() {
        if (this.wechatPayConfig == null) {
            this.wechatPayConfig = new WxPayConfig();
            this.wechatPayConfig.setAppId(this.tempWechatConfig.getAppId());
            this.wechatPayConfig.setMchId(this.tempWechatConfig.getMch_id());
            this.wechatPayConfig.setMchKey(this.tempWechatConfig.getPayKey());
            this.wechatPayConfig.setTradeType("NATIVE");
            this.wechatPayConfig.setNotifyUrl(this.tempWechatConfig.getNotifyUrl());

            this.wxPayService = new WxPayServiceImpl();
            this.wxPayService.setConfig(this.wechatPayConfig);
        }
    }

    private void checkPayment(String payCode) {

        try {

            System.out.println("支付单号：" + payCode);

            WxPayOrderQueryResult queryResult = wxPayService.queryOrder(null, payCode);
            if( queryResult == null ){
                return;
            }

            String transactionId = queryResult.getTransactionId();    // 微信订单号

            int totalfee = queryResult.getTotalFee();
            payCode = queryResult.getOutTradeNo();
            Payment payMent = payService.getOrderByCode(payCode);
            if (payMent == null) {
                return;
            }
            String tradeState = queryResult.getTradeState(); //返回的支付订单状态

            System.out.println("微信查询交易状态：" + tradeState);

            Map map = new HashMap();
            Map keyMap = new HashMap();
            keyMap.put("sn", payCode);
            JdataBean order = null;

            if ("USERPAYING".equalsIgnoreCase(tradeState)) {
                return;
            }

            if (!"SUCCESS".equalsIgnoreCase(tradeState)) {
                map.put("pay_time", new Date());
                map.put("fail_reason", queryResult.getReturnMsg());
                map.put("pay_state", Payment.PayState.FAILURE.toString());
                payService.update(map, keyMap);
                return;
            }

            System.out.println("支付订单类型：" + payMent.getOrder_type());

            //支付订单支付类型错误
            if (Payment.PayOrderType.PRODUCT_ORDER != payMent.getOrder_type()) {
                map.put("pay_time", new Date());
                map.put("pay_sn", transactionId);
                map.put("pay_state", Payment.PayState.FAILURE.toString());
                map.put("fail_reason", "支付类型错误,支付失败");
                payService.update(map, keyMap);
                return;
            }

            System.out.println("支付订单关联订单号：" + payMent.getOrder_sn());

            //商品订单为空
            if (StringUtils.isEmpty(payMent.getOrder_sn())) {
                map.put("pay_time", new Date());
                map.put("pay_sn", transactionId);
                map.put("fail_reason", "商品订单不存在,支付失败");
                payService.update(map, keyMap);
                return;
            }

            System.out.println("支付订单支付状态：" + payMent.getPay_state());

            payMent = payService.getOrderByCode(payCode);

            //支付订单不为SUCCESS
            if (Payment.PayState.SUCCESS != payMent.getPay_state()) {
                map.put("pay_state", Payment.PayState.SUCCESS.toString());
                map.put("pay_time", new Date());
                map.put("pay_sn", transactionId);
                payService.update(map, keyMap);
            }

            order = orderService.getOrderByCode(payMent.getOrder_sn());
            Integer orderStatus = order.getInt("status");
            BigDecimal orderAmount = order.getBigDecimal("pay_money");

            System.out.println("支付订单关联订单状态：" + orderStatus);
            System.out.println("支付订单关联订单金额：" + orderAmount);

            //商品订单已经成功,直接返回成功
            if (orderStatus >= 2) {
                return;
            }

            BigDecimal amount = payService.getBigDecimalAmout(payCode);//支付订单总金额

            System.out.println("支付订单已支付总金额：" + amount);

            if (amount.compareTo(orderAmount) < 0) {
                return;
            }

            if (payMent.getOrder_type() == Payment.PayOrderType.PRODUCT_ORDER) {
                orderService.updateStatusCode(payMent.getOrder_sn(), payMent.getPay_way().name(), transactionId);

                System.out.println("支付状态更新成功");

            }

            if (amount.compareTo(orderAmount) > 0) {
                BigDecimal moreAmount = amount.subtract(orderAmount);
                map.put("remark", "用户多付的金额" + moreAmount);
                payService.update(map, keyMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RedisLock("paymentTask")
    public void exectask() {
        try {
            System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");

            initWechatConfig();

            List<JdataBean> notPayList = payService.getNotPayList();
            if (notPayList != null && notPayList.size() > 0) {
                for (int i = 0, l = notPayList.size(); i < l && i < 100; i++) {
                    JdataBean jdataBean = notPayList.get(i);
                    String payCode = jdataBean.getString("sn");
                    if (StringUtils.isNotEmpty(payCode)) {
                        checkPayment(payCode);
                    }
                }
            }

            System.out.println("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
